import phaser from 'phaser';

export default class Login extends phaser.Scene {
    constructor() {
        super('Login');
    }
    create() {
        let gameWidth = <number>this.sys.game.config.width;
        let gameHeight = <number>this.sys.game.config.height;

        let body: Element = this.add.dom(gameWidth / 2, gameHeight / 2, 'div', `width:` + gameWidth + `px; height:` + gameHeight + `px; background:rgba(0,0,0,0);`).node;
        console.log('Login')
        body.innerHTML = `
        <div id="login" style="display:block;">
            <div id="loginbox">
                <div class="inputitem">
                    <span>用户</span>
                    <input id="username" value="gs" type="text">
                </div>
                <div class="inputitem">
                    <span>密码</span>
                    <input id="password" value="123456" type="password">
                </div>

                <div class="inputitem">
                    <span style="color: blue; text-decoration: underline;">注册</span>
                    <div class="loginbutton" id="loginButton">进入游戏</div>
                </div>
                <div id="login_log"></div>
            </div>
        </div>`;

        let log = body.querySelector('#login_log');
        if (log == null)
            return;

        body.querySelector('#loginButton')?.addEventListener('click', () => {
            let usernameNode:HTMLInputElement = <HTMLInputElement>body.querySelector('#username');
            let passwordNode:HTMLInputElement = <HTMLInputElement>body.querySelector('#password');
            if (usernameNode == null || passwordNode == null) {
                return
            }

            let username = usernameNode.value;
            let password = passwordNode.value;

            if (username == "" || password == "") {

                log.innerHTML = "用户名或密码不能为空";
                log.setAttribute('style', 'color: #ee0000;');
                return
            }
            console.log(username, password)
            window.client.sendAction("Login", "sign", {
                username: username,
                password: password
            });
        });


        window.client.onRecv = (recv: any) => {
            console.log(recv);
            if (recv.pack.action == "sign" && recv.pack.data.status == 0) {
                log.innerHTML = '登录成功';
                log.setAttribute('style', 'color: #005500;');
                setTimeout(() => {
                    console.log(recv.pack.data);
                    window.userInfo = recv.pack.data.userInfo
                    this.scene.start('Hall');
                    this.scene.stop('Boot');
                    this.scene.stop('Preloader');
                    this.scene.stop('Login');
                }, 500);
            }
            else {
                log.innerHTML = recv.pack.data.message;
                log.setAttribute('style', 'color: #ee0000;');
            }
        }

    }

}